package com.example.qrcodecamera;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

public class MaterialCSVImportActivity extends AppCompatActivity {
    private static final int PICK_CSV_FILE = 1001;
    private MaterialCSVDbHelper dbHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        dbHelper = new MaterialCSVDbHelper(this);

        // 启动文件选择
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.setType("text/*");
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        startActivityForResult(intent, PICK_CSV_FILE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PICK_CSV_FILE && resultCode == RESULT_OK) {
            try {
                Uri uri = data.getData();
                InputStream inputStream = getContentResolver().openInputStream(uri);
                List<MaterialCSVRecord> records = parseCSV(inputStream);

                if (dbHelper.bulkInsert(records)) {
                    Toast.makeText(this, "成功导入"+records.size()+"条记录", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(this, "部分数据导入失败", Toast.LENGTH_SHORT).show();
                }
                finish();
            } catch (Exception e) {
                Toast.makeText(this, "文件读取失败："+e.getMessage(), Toast.LENGTH_SHORT).show();
                finish();
            }
        } else {
            finish();
        }
    }

    private List<MaterialCSVRecord> parseCSV(InputStream inputStream) throws Exception {
        List<MaterialCSVRecord> records = new ArrayList<>();
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) {

            // 跳过标题行
            reader.readLine();

            String line;
            while ((line = reader.readLine()) != null) {
                line = line.trim();
                if (line.isEmpty()) continue;

                // 分割字段，保留空字段并去除引号
                String[] parts = line.split("\\s*,\\s*", -1);
                if (parts.length >= 5) {  // 检查是否至少5个字段
                    try {
                        // 解析字段并去除引号
                        String materialId = parseString(parts[0]);
                        String materialName = parseString(parts[1]);
                        double totalWeight = parseDouble(parts[2]);
                        double currentWeight = parseDouble(parts[3]);
                        String storageTime = parseString(parts[4]);

                        // 创建 MaterialCSVRecord 实例，id 由数据库自动生成，此处设为默认值0
                        MaterialCSVRecord record = new MaterialCSVRecord(
                                0,            // id（数据库自动生成，此处无需设置）
                                materialId,    // 物料编号
                                materialName,  // 物料名称
                                totalWeight,   // 总重量
                                currentWeight, // 当前重量
                                storageTime    // 入库时间
                        );
                        records.add(record);
                    } catch (NumberFormatException e) {
                        Log.w("CSVParse", "数值格式错误，跳过行: " + line);
                    }
                } else {
                    Log.w("CSVParse", "字段不足，跳过行: " + line);
                }
            }
        } catch (Exception e) {
            Log.e("CSVParse", "文件解析异常", e);
            throw e;
        }
        return records;
    }

    // 辅助方法：去除引号并处理空值
    private String parseString(String value) {
        if (value == null || value.equalsIgnoreCase("null")) {
            return "";
        }
        return value.trim().replaceAll("^\"|\"$", "");
    }

    // 辅助方法：解析数值并去除非数字字符
    private double parseDouble(String value) {
        try {
            String cleanedValue = value.replaceAll("\"", "").replaceAll("[^\\d.-]", "");
            return Double.parseDouble(cleanedValue);
        } catch (NumberFormatException e) {
            Log.w("NumberParse", "无效数值: " + value);
            return 0.0;
        }
    }
}